<?php
	namespace service\ai;

	use GuzzleHttp\Client;
	use think\Config;

	class AiService{
		private $engine;
		private $config = [];
		private $providers = [
			'dify' => 'Dify',
		];

		public function __construct($options = [])
		{
			$this->config = array_merge($this->config, is_array($options) ? $options : []);

			//注册服务提供者
			if (isset($this->config['key'])){
				$this->engine = $this->registerProviders();
			}

		}

		/**
		 * 注册服务提供者
		 */
		private function registerProviders()
		{
			$objname = __NAMESPACE__ . "\\engine\\" . $this->providers[$this->config['key']];
			return new $objname($this->config);
		}

		public function getReply($user,$question){
			// 清除当前的输出缓冲区并禁止输出缓冲，以确保数据能够即时发送给客户端
			ob_end_clean();
			// 设置响应头，指定使用SSE协议，禁用缓存并保持连接 alive
			header('Content-Type: text/event-stream');
			header('Cache-Control: no-cache');
			header('Connection: keep-alive');
			// 对于使用Nginx服务器的情况，禁用缓冲以确保数据即时发送
			header('X-Accel-Buffering: no');

			return $this->engine->getReply($user,$question);
		}

		public function textReply($user,$question){
			return $this->engine->textReply($user,$question);
		}
	}